package xgorm

import (
	"encoding/json"
	"fmt"
	"strings"
)

// SQL语句进行别名解析，用于left join/where使用
//
//	column	待拼接的字符串，允许值类型为：[]number,[]string
//	alias	该字段别名
//	tables	使用gorm等工具时的AS别名，会追加() AS xxxx形式，空字符串则不追加
func DataColumnAsString(column []string, alias, tables string) string {
	if len(column) <= 0 {
		return "SELECT '' AS " + alias
	}
	temps := []string{}
	for i := 0; i < len(column); i++ {
		if i == 0 {
			temps = append(temps, "SELECT '"+column[i]+"' AS "+alias+" UNION ALL")
			continue
		} else if i == len(column)-1 {
			temps = append(temps, "SELECT '"+column[i]+"'")
			continue
		}
		temps = append(temps, "SELECT '"+column[i]+"' UNION ALL")
	}
	if tables != "" {
		return "(" + strings.Join(temps, " ") + ") AS " + tables
	}
	return strings.Join(temps, " ")
}

// 多维数组转SQL
func DataColumnAsList(column [][]string, alias []string, tables string) string {
	if len(column) <= 0 {
		return "SELECT ''"
	}
	temps := []string{}
	for i := 0; i < len(column); i++ {
		childs := []string{}
		for j := 0; j < len(column[i]); j++ {
			if j < len(alias) {
				childs = append(childs, column[i][j]+" AS "+alias[j])
			} else {
				childs = append(childs, column[i][j]+" AS "+fmt.Sprintf("column_%d", j+1))
			}
		}
		if i == len(column)-1 {
			temps = append(temps, "SELECT "+strings.Join(childs, ","))
			continue
		}
		temps = append(temps, "SELECT "+strings.Join(childs, ",")+" UNION ALL")
	}
	if tables != "" {
		return "(" + strings.Join(temps, " ") + ") AS " + tables
	}
	return strings.Join(temps, " ")
}

// 未知类型转义
func DataColumnAs(column any, alias, tables string) string {
	temp := []string{}
	switch col := column.(type) {
	case []int8, []uint8, []int16, []uint16, []int, []uint, []int32, []uint32, []int64, []uint64:
		temp = DataColumnAsIntString(col)
	case []float32, []float64:
		temp = DataColumnAsFloatString(col)
	case []string:
		temp = col
	default:
		return DataColumnAsString(temp, alias, tables)
	}
	return strings.ReplaceAll(DataColumnAsString(temp, alias, tables), "'", "")
}

// 将整数类型转换为字符串类型
//
//	col	待转换的变量数据
func DataColumnAsIntString(col any) []string {
	temp := []int64{}
	err := jany(col, &temp)
	if err != nil {
		return []string{}
	}
	news := []string{}
	for i := 0; i < len(temp); i++ {
		news = append(news, fmt.Sprintf("%d", temp[i]))
	}
	return news
}

// 将整数类型转换为字符串类型
//
//	col	待转换的变量数据
func DataColumnAsFloatString(col any) []string {
	temp := []float64{}
	err := jany(col, &temp)
	if err != nil {
		return []string{}
	}
	news := []string{}
	for i := 0; i < len(temp); i++ {
		news = append(news, fmt.Sprintf("%g", temp[i]))
	}
	return news
}

// 结构体转换【通过json进行转换，所以建立结构体时请注意json对应】
//
//	old	待转换的变量类型
//	new	转换后的变量存储位置【此值需要为指针】
func jany(old, new any) error {
	// old转[]byte
	b, err := json.Marshal(old)
	if err != nil {
		return err
	}
	return json.Unmarshal(b, new)
}
